package com.dog.basics.service.mtkj.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dog.basics.bean.dto.admin.mtkj.LockPassAddDto;
import com.dog.basics.bean.dto.admin.mtkj.LockPassFromDto;
import com.dog.basics.bean.model.mtkj.*;
import com.dog.basics.bean.vo.admin.mtkj.LockPassVo;
import com.dog.basics.bean.vo.api.mtkj.ApiHospitalCostVo;
import com.dog.basics.bean.vo.api.mtkj.ApiLockPassVo;
import com.dog.basics.common.util.PageParam;
import com.dog.basics.dao.mtkj.*;
import com.dog.basics.security.util.SecurityUtils;
import com.dog.basics.service.mtkj.IMtDeviceLockPassService;
import lombok.AllArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备锁通道表 服务实现类
 * </p>
 *
 * @author wph
 * @since 2020-09-30
 */
@Service
@AllArgsConstructor
public class MtDeviceLockPassServiceImpl extends ServiceImpl<MtDeviceLockPassMapper, MtDeviceLockPass> implements IMtDeviceLockPassService {
    private final MtDeviceLockMapper mtDeviceLockMapper;
    private final MtDeviceOrderMapper mtDeviceOrderMapper;
    private final MtDeviceWheelchairMapper mtDeviceWheelchairMapper;
    private final MtDeviceDepositMapper mtDeviceDepositMapper;
    private final MtDeviceHospitalMapper mtDeviceHospitalMapper;
    private final MtDeviceHospitalCostMapper mtDeviceHospitalCostMapper;
    private final MtDeviceHospitalWheelchairMapper mtDeviceHospitalWheelchairMapper;
    private final RedissonClient redissonClient;

    /**
     * 分页的条件公用类
     *
     * @param name,mobile
     * @param lockCodeIds
     */
    public List<Long> getlockCodeIdsWhere(String name, List<Long> lockCodeIds) {
        List<Long> collect = mtDeviceLockMapper.selectList(Wrappers.<MtDeviceLock>lambdaQuery().like(StrUtil.isNotBlank(name), MtDeviceLock::getDevCode, name)).stream().map(e -> e.getId()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            lockCodeIds = collect;
        } else {
            lockCodeIds.add(-2L);
        }
        return lockCodeIds;
    }

    /**
     * 分页的条件公用类
     *
     * @param name,mobile
     * @param codeIds
     */
    public List<Long> getCodeIdsWhere(String name, List<Long> codeIds) {
        List<Long> collect = mtDeviceWheelchairMapper.selectList(Wrappers.<MtDeviceWheelchair>lambdaQuery().like(StrUtil.isNotBlank(name), MtDeviceWheelchair::getWheeCode, name)).stream().map(e -> e.getId()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            codeIds = collect;
        } else {
            codeIds.add(-2L);
        }
        return codeIds;
    }

    /**
     * @Description: 分页设备锁通道
     * @Param: status
     * @return: IPage<LockPassVo>
     * @Author: wph
     * @Date:
     */
    @Override
    public IPage<LockPassVo> getPageList(PageParam page, LockPassFromDto obj) {
        // 判断所属轮椅编号ID
        List<Long> codeIds = CollUtil.newArrayList();
        if (StrUtil.isNotBlank(obj.getWheeCode())) {
            codeIds = getCodeIdsWhere(obj.getWheeCode(), codeIds);
        }
        // 判断所属锁编号ID
        List<Long> lockCodeIds = CollUtil.newArrayList();
        if (StrUtil.isNotBlank(obj.getLockCode())) {
            lockCodeIds = getlockCodeIdsWhere(obj.getLockCode(), lockCodeIds);
        }
        IPage iPage = this.page(page, new LambdaQueryWrapper<MtDeviceLockPass>()
                .in(CollUtil.isNotEmpty(codeIds), MtDeviceLockPass::getWheeId, codeIds)
                .in(CollUtil.isNotEmpty(lockCodeIds), MtDeviceLockPass::getLockId, lockCodeIds)
                .eq(ObjectUtil.isNotNull(obj.getPassStatus()), MtDeviceLockPass::getPassStatus, obj.getPassStatus())
                .eq(ObjectUtil.isNotNull(obj.getWheeId()), MtDeviceLockPass::getWheeId, obj.getWheeId())
                .eq(ObjectUtil.isNotNull(obj.getLockId()), MtDeviceLockPass::getLockId, obj.getLockId())
                .orderBy(Boolean.TRUE, obj.getIsOrderByAvg(), MtDeviceLockPass::getCreateTime));
        List<MtDeviceLockPass> records = iPage.getRecords();
        iPage.setRecords(records.stream().map(e -> {
            LockPassVo newsVo = BeanUtil.copyProperties(e, LockPassVo.class);
            //查询
            MtDeviceWheelchair mtDeviceWheelchair = mtDeviceWheelchairMapper.selectById(e.getWheeId());
            MtDeviceLock mtDeviceLock = mtDeviceLockMapper.selectById(e.getLockId());
            newsVo.setLockCode(ObjectUtil.isNotNull(mtDeviceLock) ? mtDeviceLock.getDevCode() : "");
            newsVo.setWheeCode(ObjectUtil.isNotNull(mtDeviceWheelchair) ? mtDeviceWheelchair.getWheeCode() : "");
            newsVo.setWheeType(ObjectUtil.isNotNull(mtDeviceWheelchair) ? mtDeviceWheelchair.getWheeType() : 0);
            return newsVo;
        }).collect(Collectors.toList()));
        return iPage;
    }

    /**
     * @Description: 设备锁详情
     * @Param: id
     * @return: ApiLockVo
     * @Author: wph
     * @Date:
     */
    @Override
    @Async
    public ApiLockPassVo getApiObjXq(Long id) {
        ApiLockPassVo apiLockPassVo = new ApiLockPassVo();
        String key = "dec__lock_pass" + id;
        RLock lock = redissonClient.getLock(key);
        try {
            Boolean flage = lock.tryLock(1, 5, TimeUnit.SECONDS);
            if (flage) {
                //判断是够有未支付的订单
                List<MtDeviceOrder> orderList1 = mtDeviceOrderMapper.selectList(Wrappers.<MtDeviceOrder>lambdaQuery().eq(MtDeviceOrder::getOrderUserId, SecurityUtils.getUser().getUserId()).eq(MtDeviceOrder::getOrderPayState, 0).eq(MtDeviceOrder::getOrderState, 0));
                Validator.validateFalse(CollUtil.isNotEmpty(orderList1), "您还有使用中的订单!");
                List<MtDeviceOrder> orderList = mtDeviceOrderMapper.selectList(Wrappers.<MtDeviceOrder>lambdaQuery().eq(MtDeviceOrder::getOrderUserId, SecurityUtils.getUser().getUserId()).eq(MtDeviceOrder::getOrderPayState, 0).eq(MtDeviceOrder::getOrderState, 1));
                Validator.validateFalse(CollUtil.isNotEmpty(orderList), "您还有未支付的订单!");
                MtDeviceLockPass obj = this.getById(id);
                Validator.validateNotNull(obj, "无此数据!");
                Validator.validateFalse(Validator.equal(obj.getPassStatus(), 0), "该通道未绑定设备");
                Validator.validateFalse(Validator.equal(obj.getPassStatus(), 2), "该通道未已经故障");
                MtDeviceWheelchair mtDeviceWheelchair = mtDeviceWheelchairMapper.selectById(obj.getWheeId());
                Validator.validateNotNull(mtDeviceWheelchair, "设备不存在!");
                Validator.validateEqual(mtDeviceWheelchair.getUseState(), 0, "设备维护中,请更换其它设备!");
                MtDeviceLock dogNews = mtDeviceLockMapper.selectById(obj.getLockId());
                Validator.validateNotNull(dogNews, "设备锁不存在!");
                //判断是否绑定
                Validator.validateFalse(Validator.equal(dogNews.getDevAgentUserId(), 1L), "该设备锁还未绑定");
                Validator.validateFalse(Validator.equal(dogNews.getHospitalId(), 1L), "该设备锁还未绑定");
                Validator.validateEqual(dogNews.getDevInitializeState(), 1, "该设备还未初始化");
                Validator.validateFalse(Validator.equal(dogNews.getDevStatus(), 2), "该设备锁已经故障");
                MtDeviceHospital mtDeviceHospital = mtDeviceHospitalMapper.selectById(dogNews.getHospitalId());
                Validator.validateNotNull(mtDeviceHospital, "医院不存在!");

                apiLockPassVo.setDevOnlineState(dogNews.getDevOnlineState());
                apiLockPassVo.setLockCode(dogNews.getDevCode());
                apiLockPassVo.setLockId(dogNews.getId());
                apiLockPassVo.setLyName(dogNews.getDevBluetoothName());
                BeanUtil.copyProperties(obj, apiLockPassVo);
                apiLockPassVo.setWheeCode(mtDeviceWheelchair.getWheeCode());
                apiLockPassVo.setWheeName(mtDeviceWheelchair.getWheeName());
                List<MtDeviceHospitalCost> mtDeviceHospitalCostList = mtDeviceHospitalCostMapper.selectList(Wrappers.<MtDeviceHospitalCost>lambdaQuery().eq(MtDeviceHospitalCost::getDeviceHospitalId, dogNews.getHospitalId()).eq(MtDeviceHospitalCost::getWheeType, mtDeviceWheelchair.getWheeType()).orderByDesc(MtDeviceHospitalCost::getCreateTime));
                Validator.validateTrue(CollUtil.isNotEmpty(mtDeviceHospitalCostList), "该医院未完善此类型设备收费标准!");
                ApiHospitalCostVo apiHospitalCostVo = new ApiHospitalCostVo();
                BeanUtil.copyProperties(mtDeviceHospitalCostList.get(0), apiHospitalCostVo);
                apiHospitalCostVo.setDeviceHospitalName(mtDeviceHospital.getHospitalName());
                apiLockPassVo.setApiHospitalCostVo(apiHospitalCostVo);
                //判断是否缴纳押金
                List<MtDeviceDeposit> list = mtDeviceDepositMapper.selectList(Wrappers.<MtDeviceDeposit>lambdaQuery().eq(MtDeviceDeposit::getDepositState, 1).eq(MtDeviceDeposit::getDepositUserId, SecurityUtils.getUser().getUserId()).orderByDesc(MtDeviceDeposit::getCreateTime));
                if (CollUtil.isNotEmpty(list)) {
                    //判断类型和医院
                    MtDeviceDeposit mtDeviceDeposit = list.get(0);
                    //相同的医院
                    if (Validator.equal(mtDeviceDeposit.getHospitalId(), dogNews.getHospitalId())) {
                        //  Validator.validateEqual(mtDeviceDeposit.getHospitalId(), dogNews.getHospitalId(), "您缴纳的押金不是该医院的,如需使用其他产品请退押金之后重新扫描二维码!");
                        if (Validator.equal(mtDeviceDeposit.getWheeType(), mtDeviceWheelchair.getWheeType())) {
                            //在判断金额是否相同costWheelchairDeposit
                            if (mtDeviceDeposit.getDepositMoney().compareTo(mtDeviceHospitalCostList.get(0).getCostWheelchairDeposit()) >= 0) {
                                apiLockPassVo.setSfDeposit(1);
                            } else {
                                if (mtDeviceWheelchair.getWheeType() == 0) {
                                    Validator.validateTrue(Boolean.FALSE, "轮椅押金发生变化,如需使用其他产品请退押金之后重新扫描二维码!");
                                } else if (mtDeviceWheelchair.getWheeType() == 1) {
                                    Validator.validateTrue(Boolean.FALSE, "平推车押金发生变化,如需使用其他产品请退押金之后重新扫描二维码!");
                                } else {
                                    Validator.validateTrue(Boolean.FALSE, "陪护床押金发生变化,如需使用其他产品请退押金之后重新扫描二维码!");
                                }
                            }
                        } else {
                            if (mtDeviceWheelchair.getWheeType() == 0) {
                                Validator.validateTrue(Boolean.FALSE, "正在使用的产品是轮椅,如需使用其他产品请退押金之后重新扫描二维码!");
                            } else if (mtDeviceWheelchair.getWheeType() == 1) {
                                Validator.validateTrue(Boolean.FALSE, "正在使用的产品是平推车,如需使用其他产品请退押金之后重新扫描二维码!");
                            } else {
                                Validator.validateTrue(Boolean.FALSE, "正在使用的产品是陪护床,如需使用其他产品请退押金之后重新扫描二维码!");
                            }
                        }
                        //不同的医院
                    } else {
                        if (Validator.equal(mtDeviceDeposit.getWheeType(), mtDeviceWheelchair.getWheeType())) {
                            //在判断金额是否相同costWheelchairDeposit
                            if (mtDeviceDeposit.getDepositMoney().compareTo(mtDeviceHospitalCostList.get(0).getCostWheelchairDeposit()) >= 0) {
                                apiLockPassVo.setSfDeposit(1);
                            } else {
                                if (mtDeviceWheelchair.getWheeType() == 0) {
                                    Validator.validateTrue(Boolean.FALSE, "您缴纳的轮椅押金不是该医院的,如需使用其他产品请退押金之后重新扫描二维码!");
                                } else if (mtDeviceWheelchair.getWheeType() == 1) {
                                    Validator.validateTrue(Boolean.FALSE, "您缴纳的平推车押金不是该医院的,如需使用其他产品请退押金之后重新扫描二维码!");
                                } else {
                                    Validator.validateTrue(Boolean.FALSE, "您缴纳的陪护床押金不是该医院的,如需使用其他产品请退押金之后重新扫描二维码!");
                                }
                            }
                        } else {
                            if (mtDeviceWheelchair.getWheeType() == 0) {
                                Validator.validateTrue(Boolean.FALSE, "正在使用的产品是轮椅,如需使用其他产品请退押金之后重新扫描二维码!");
                            } else if (mtDeviceWheelchair.getWheeType() == 1) {
                                Validator.validateTrue(Boolean.FALSE, "正在使用的产品是平推车,如需使用其他产品请退押金之后重新扫描二维码!");
                            } else {
                                Validator.validateTrue(Boolean.FALSE, "正在使用的产品是陪护床,如需使用其他产品请退押金之后重新扫描二维码!");
                            }
                        }

                    }

                } else {
                    apiLockPassVo.setSfDeposit(0);
                }
                apiLockPassVo.setHospitalId(dogNews.getHospitalId());

            } else {
                Validator.validateTrue(Boolean.FALSE, "该通道设备正在被使用!");

            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //TODO:释放锁
            if (ObjectUtil.isNotNull(lock) && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }

        }
        return apiLockPassVo;
    }

    /**
     * @Description: 增加设备锁通道轮椅关联
     * @Param: obj
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/19  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveObj(LockPassAddDto obj) {
        MtDeviceLockPass mtDeviceLockPass = this.getById(obj.getId());
        Validator.validateNotNull(mtDeviceLockPass, "设备锁通道不存在!");
        Validator.validateFalse(Validator.equal(mtDeviceLockPass.getPassStatus(), 2), "设备通道故障!");
        MtDeviceLock dogNews = mtDeviceLockMapper.selectById(mtDeviceLockPass.getLockId());
        Validator.validateNotNull(dogNews, "设备锁不存在!");
        MtDeviceWheelchair mtDeviceWheelchair = mtDeviceWheelchairMapper.selectById(obj.getWheeId());
        Validator.validateNotNull(mtDeviceWheelchair, "轮椅不存在!");
        //判断轮椅是否绑定过
        List<MtDeviceLockPass> list = this.list(Wrappers.<MtDeviceLockPass>lambdaQuery().ne(MtDeviceLockPass::getId, obj.getId()).eq(MtDeviceLockPass::getWheeId, obj.getWheeId()));
        Validator.validateFalse(CollUtil.isNotEmpty(list), "该轮椅已经绑定过!");
        List<MtDeviceHospitalWheelchair> list1 = mtDeviceHospitalWheelchairMapper.selectList(Wrappers.<MtDeviceHospitalWheelchair>lambdaQuery().eq(MtDeviceHospitalWheelchair::getHospitalId, dogNews.getHospitalId()).eq(MtDeviceHospitalWheelchair::getWheelchairId, obj.getWheeId()));
        Validator.validateTrue(CollUtil.isNotEmpty(list1), "该轮椅和锁不在一个医院!");
        mtDeviceLockPass.setWheeId(obj.getWheeId());
        mtDeviceLockPass.setPassStatus(1);
        mtDeviceLockPass.setUpdateTime(DateUtil.currentSeconds());
        mtDeviceLockPass.setUpdateBy(SecurityUtils.getSysUser().getUserId());
        Validator.validateTrue(this.updateById(mtDeviceLockPass), "修改数据失败!");
        return Boolean.TRUE;
    }

    /**
     * @Description: 修改设备锁通道轮椅关联
     * @Param: obj
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/19  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editObj(LockPassAddDto obj) {
        MtDeviceLockPass mtDeviceLockPass = this.getById(obj.getId());
        Validator.validateNotNull(mtDeviceLockPass, "设备锁通道不存在!");
        MtDeviceLock dogNews = mtDeviceLockMapper.selectById(mtDeviceLockPass.getLockId());
        Validator.validateNotNull(dogNews, "设备锁不存在!");
        MtDeviceWheelchair mtDeviceWheelchair = mtDeviceWheelchairMapper.selectById(obj.getWheeId());
        Validator.validateNotNull(mtDeviceWheelchair, "轮椅不存在!");
        //判断轮椅是否绑定过
        List<MtDeviceLockPass> list = this.list(Wrappers.<MtDeviceLockPass>lambdaQuery().ne(MtDeviceLockPass::getId, obj.getId()).eq(MtDeviceLockPass::getWheeId, obj.getWheeId()));
        Validator.validateFalse(CollUtil.isNotEmpty(list), "该轮椅已经绑定过!");
        List<MtDeviceHospitalWheelchair> list1 = mtDeviceHospitalWheelchairMapper.selectList(Wrappers.<MtDeviceHospitalWheelchair>lambdaQuery().eq(MtDeviceHospitalWheelchair::getHospitalId, dogNews.getHospitalId()).eq(MtDeviceHospitalWheelchair::getWheelchairId, obj.getWheeId()));
        Validator.validateTrue(CollUtil.isNotEmpty(list1), "该轮椅和锁不在一个医院!");
        mtDeviceLockPass.setWheeId(obj.getWheeId());
        mtDeviceLockPass.setPassStatus(1);
        mtDeviceLockPass.setUpdateTime(DateUtil.currentSeconds());
        mtDeviceLockPass.setUpdateBy(SecurityUtils.getSysUser().getUserId());
        Validator.validateTrue(this.updateById(mtDeviceLockPass), "修改数据失败!");
        return Boolean.TRUE;
    }

    /**
     * @Description: 删除设备锁通道轮椅关联
     * @Param: ids
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/19  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteObj(Long id) {
        MtDeviceLockPass mtDeviceLockPass = this.getById(id);
        Validator.validateNotNull(mtDeviceLockPass, "设备锁通道不存在!");
        Validator.validateEqual(mtDeviceLockPass.getPassLockStatus(), 0, "该通道正在被使用不能删除");
        mtDeviceLockPass.setWheeId(-1L);
        mtDeviceLockPass.setPassStatus(0);
        mtDeviceLockPass.setPassLockStatus(0);
        mtDeviceLockPass.setUpdateTime(DateUtil.currentSeconds());
        mtDeviceLockPass.setUpdateBy(SecurityUtils.getSysUser().getUserId());
        Validator.validateTrue(this.updateById(mtDeviceLockPass), "删除数据失败!");
        return Boolean.TRUE;
    }

    /**
     * @功能描述: 修改设备锁通信息
     * @author He
     * @date 2020/11/27
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editMtDeviceLockPassById(MtDeviceLockPass deviceLockPass) {
        Validator.validateTrue(this.updateById(deviceLockPass), "设备锁通道更新失败!");
        return Boolean.TRUE;
    }
}
